package com.om.base;



import com.om.common.ConstantsUtil;
import com.om.common.TimeStampToInt;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;




public class Utils {
	
	public static void WriteLog(String strLog) {
		if(ConstantsUtil.isdebug){
			System.out.println(TimeStampToInt.systemTime()+":>"+strLog);
		}
	}
	
	public static boolean IsNullOrEmpty(Object obj){
		if (obj == null)
			return true;
		
		if ("".equals(obj))
			return true;

		return false;
	}

	/***
	 * 通过方法名称调用对象的非方法
	 * @param owner 宿主对象
	 * @param methodName 方法名称
	 * @param args  方法需要的参数值的数组
	 * @return 方法的返回值
	 * @throws Exception
	 */
	public static Object InvokeMethodByName(Object owner, String methodName,
			Object[] args) throws Exception {
		
		Class ownerClass = owner.getClass();

		Class[] argsClass = new Class[args.length];

		int i = 0;
		for (int j = args.length; i < j; ++i) {
			argsClass[i] = args[i].getClass();
		}

		return ownerClass.getMethod(methodName, argsClass).invoke(owner, args);
	}
	
	public static String HtmlSpecialChars(String str) {
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		//str = str.replaceAll("\r\n", "");
		return str;
	}
	
    /**
     * 获取对象字段值
     * @param owner 宿主对象
     * @param fieldName 字段名称
     * @return 字段的值
     */
	public static Object GetProperty(Object owner, String fieldName)
			throws Exception {
		
		Object property = PropertyUtils.getProperty(owner, fieldName);		
		return property;
	}
	
	
	
	
	
	/**
	 * @param obj 宿主对象
	 * @param name 字段的名称
	 * @param value 需要设置的值
	 */
	public static void setFieldValueByName(Object obj,String name,Object value){
		
		try{
			
			BeanUtils.setProperty(obj, name, value);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	public Object GetStaticProperty(String className, String fieldName)
			throws Exception {
		Class ownerClass = Class.forName(className);

		Object property = ownerClass.getField(fieldName).get(ownerClass);

		return property;
	}

	/**
	 * 通过名称调用类的静态方法
	 * @param className 类的名称
	 * @param methodName 需要调用的方法的名称
	 * @param args 方法需要的参数值的数组
	 * @return 方法的返回值
	 * @throws Exception
	 */
	public Object InvokeStaticMethodByName(String className, String methodName,
			Object[] args) throws Exception {
		Class ownerClass = Class.forName(className);

		Class[] argsClass = new Class[args.length];

		int i = 0;
		for (int j = args.length; i < j; ++i) {
			argsClass[i] = args[i].getClass();
		}

		Method method = ownerClass.getMethod(methodName, argsClass);

		return method.invoke(null, args);
	}

	public static String GetXmlValue(AbstractBean bean) {
		String strXml = "";
		for (int i = 0; i < bean.Field.length; ++i) {
			String field = bean.Field[i];
			String value = bean.getStringValue(field);
			strXml = strXml + "  <" + field + ">" + value + "</" + field
					+ ">\n";
		}
		if ((strXml != null) && (!("".equals(strXml)))) {
			strXml = "<" + bean.TABLE_NAME + ">\r\n" + strXml + "</"
					+ bean.TABLE_NAME + ">\r\n";
		}
		return strXml;
	}

	
	
	

	
	
	

	
	/**
	 * 根据默认的配置获取一个被当前线程托管的可用数据库连接
	 * @return 一个可用的数据库连接
	 * @throws SQLException
	 */
	public static Connection GetOpenedConnection() throws SQLException {
		Connection con = null;
		try{
			con = DBConnectionManager.getInstance().getConnection();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return con;
	}
	
	
	public static Connection GetOpenedConnection(boolean forceOpenNew) throws SQLException {
		Connection con = null;
		try{
			con = DBConnectionManager.getInstance().getConnection(forceOpenNew);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return con;
	}
	
	public static void SetOpenedConnection(Connection con){
		DBConnectionManager.getInstance().setConnection(con);
	}
	
	public static void SetOpenedConnection(String name,Connection con){
		DBConnectionManager.getInstance().setConnection(name,con);
	}
	
	
	
	/**
	 * 根据默认的配置获取一个被当前线程托管的用于写操作的的数据连接
	 * @return 一个可用的数据库连接
	 * @throws SQLException
	 */
	public static Connection GetOpenedWriteConnection() throws SQLException {

		Connection con = null;
		try{
			con = DBConnectionManager.getInstance().getWriteConnection();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return con;
	}

	

	
	
	/**
	 * 根据键获取Get,Post方式提交的参数值
	 * @param request HttpServletRequest对象
	 * @param key 参数名称
	 * @return 参数值
	 */
	public static String GetParameter(HttpServletRequest request, String key) {
		String value = "";
		try {
			if (request.getParameterMap().containsKey(key)) {
				value = request.getParameter(key);
			}

			if (("".equals(value)) && (request.getAttribute(key) != null)) {
				value = request.getAttribute(key) + "";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return value;
	}
	
	private static void loadSelfDate(String xmlDate, AbstractBean bean,
			Connection con) throws Exception {
		XmlParse parse = new XmlParse(xmlDate, bean, bean.TABLE_NAME);
		List list = parse.getBeanList();
		for (int i = 0; i < list.size(); ++i) {
			AbstractBean Item = (AbstractBean) list.get(i);
			Item.insertItem();
		}
	}

	/**
	 * 以指定的编码方式读取文件内容，以字符串的形式返回
	 * @param fileName 文件的绝对路径（目录+完整文件名）
	 * @param encode 读取的编码方式（UTF-8,GBK。。。）
	 * @return 包含文件内容的字符串
	 */
	public static String ReadFileByLines(String fileName,String encode) {
		String strContent = "";
		File file = new File(fileName);
		BufferedReader reader = null;
		InputStreamReader insReader = null;
		try {
			 insReader = new InputStreamReader(new FileInputStream(file),encode);
					
			reader = new BufferedReader(insReader);
			
			String tempString = null;
			int line = 1;

			while ((tempString = reader.readLine()) != null) {
				++line;
				strContent = strContent + tempString;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException localIOException2) {
				}
			}
		}
		return strContent;
	}

	/**
	 * 把一个AbstractBean对象填充到一个模板上，结果以字符串返回
	 * @param bean 需要合并的AbstractBean对象
	 * @param template 模板字符串
	 * @param startSymbol 占位符的开始字符
	 * @param endSymbol  占位符的结束字符
	 * @return 替换后的内容字符串
	 */
	public static String MergeTemplate(AbstractBean bean, String template,
			String startSymbol,String endSymbol) {
		String strHtml = "";
		HashMap map = new HashMap();
		for (int i = 0; i < bean.Field.length; ++i) {
			String key = bean.Field[i];
			Object value = bean.get(key);
			map.put(key, value);
		}
		strHtml = MergeTemplate(map, template, startSymbol,endSymbol);
		return strHtml;
	}
	
	
	
	/**
	 * 把一个HashMap对象填充到一个模板上，结果以字符串返回
	 * @param map 需要合并的HashMap对象
	 * @param template 模板字符串
	 * @param startSymbol 占位符的开始字符
	 * @param endSymbol  占位符的结束字符
	 * @return 替换后的内容字符串
	 */
	public static String MergeTemplate(HashMap<String, Object> map,
			String template, String startSymbol,String endSymbol) {
		String strHtml = "";
		try {
			
			Object[] keys = map.keySet().toArray();
			for (int i = 0; i < keys.length; ++i) {
				String key = (String) keys[i];
				Object value = map.get(key);
				if (value == null)
					value = "";
				String tag = startSymbol+ key + endSymbol;
				if (template.indexOf(tag) == -1)
					continue;
				template = template.replace(tag, value.toString());
			}

			strHtml = template;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return strHtml;
	}
	
	/**
	 * 把一个字符串进行压缩
	 * @param str 需要压缩的字符串
	 * @return 压缩后的字符串
	 * @throws IOException
	 */
	public static String CompressString(String str) throws IOException {
		if ((str == null) || (str.length() == 0)) {
			return str;
		}
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(str.getBytes());
		gzip.close();
		return out.toString("ISO-8859-1");
        
	}
	
	/**
	 * 对一个压缩过的字符串进行解压缩
	 * @param str 需要解压缩的字符串
	 * @return 解压缩后的字字符串
	 * @throws IOException
	 */
	public static String DecompressString(String str) throws IOException {
		if ((str == null) || (str.length() == 0)) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(
				str.getBytes("ISO-8859-1"));
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0) {
			out.write(buffer, 0, n);
		}
		return out.toString();
	}
	
	/**
	 * 对一个url进行Post的模拟
	 * @param url 需要post的url
	 * @param param 需要post的参数集合
	 * @return 把url的返回结果以字符串的形式返回
	 */
	public static String SendPost(String url, String param) {
		String result = "";
		URL httpurl = null;
		try {
			httpurl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) httpurl
					.openConnection();
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("accept", "*/*");
			//httpConn.setRequestProperty("Content-type", "text/html");
			httpConn.setRequestProperty("Accept-Charset", "utf-8");
			httpConn.setRequestProperty("connection", "Keep-Alive");
			httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			httpConn.setRequestProperty("contentType", "utf-8");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
            
			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
			//out.print(URLEncoder.encode(param+"", "UTF-8"));
			out.print(param);
			out.flush();
			out.close();

			BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
			String line="";
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			in.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
	
	public static HashMap<String, Object> SendRequest(String url, String param) {
		String result = "";
		URL httpurl = null;
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			httpurl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) httpurl
					.openConnection();
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("accept", "*/*");

			httpConn.setRequestProperty("Accept-Charset", "utf-8");
			httpConn.setRequestProperty("connection", "Keep-Alive");
			httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			httpConn.setRequestProperty("contentType", "utf-8");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
			//out.print(URLEncoder.encode(param+"", "UTF-8"));
			out.print(param);
			out.flush();
			out.close();
			
			Map hfs=httpConn.getHeaderFields();
			String cookieValue=httpConn.getHeaderField("Set-Cookie");
            System.out.println("cookie value:"+cookieValue);
            String sessionId=cookieValue.substring(0, cookieValue.indexOf(";"));
            sessionId = sessionId.split("\\=")[1];
            map.put("SessionId", sessionId);
            
			BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
			String line="";
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			in.close();
			map.put("responseText", result);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return map;
	}
	
	
	public static String GetSessionId(String strUrl, String param){
        OutputStream out=null;
        InputStream in=null;
        String sessionId ="";
        try {
            URL url=new URL(strUrl);
            HttpURLConnection con=(HttpURLConnection)url.openConnection();
            con.setRequestMethod("POST");
            
            //打印请求头信息
            Map hfs=con.getHeaderFields();
            Set<String> keys=hfs.keySet();
            for(String str:keys){
                List<String> vs=(List)hfs.get(str);
                System.out.print(str+":");
                for(String v:vs){
                    System.out.print(v+"\t");
                }
                System.out.println();
            }
            System.out.println("-----------------------");
            String cookieValue=con.getHeaderField("Set-Cookie");
            System.out.println("cookie value:"+cookieValue);
            sessionId=cookieValue.substring(0, cookieValue.indexOf(";"));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(in!=null)
                    in.close();
                if(out!=null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sessionId;
    }
	
	
	/**
	 * 对一个url进行get的模拟
	 * @param url 需要get的url
	 * @param param 需要get的参数集合
	 * @return 把url的返回结果以字符串的形式返回
	 */
	/*public static String SendGet(String url, String param) {
		String result = "";
		try {
			String urlName = url ;
			if( !"".equals(param+"")){
				urlName = "?"+param;
			}

			URL U = new URL(urlName);
			URLConnection connection = U.openConnection();
			connection.connect();

			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "UTF-8"));
			String line = "";
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			in.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}*/
	
	
	public static String SendGet(String url, String param) {  
        String result = "";  
        BufferedReader in = null;  
        try {  
            String urlName = url + "?" + param;  
            URL realUrl = new URL(urlName);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
            conn.setRequestProperty("Content-type", "text/html");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
			
            // 建立实际的连接  
            conn.connect();  
            // 获取所有响应头字段  
           Map<String, List<String>> map = conn.getHeaderFields();  
            // 遍历所有的响应头字段  
            for (String key : map.keySet()) {  
                System.out.println(key + "--->" + map.get(key));  
            }  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += "\n" + line;  
            }  
        } catch (Exception ex) {  
        	ex.printStackTrace();
        	System.out.println("发送GET请求出现异常！" + ex.getMessage());  
              
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }  
	
	

	
	public static String GetCookieValue(HttpServletRequest request, String key) {
		String value = "";
		try {
			Cookie[] lst = request.getCookies();
			if(lst !=null){
				for (int i = 0; i < lst.length; i++ ) {
					if (lst[i].getName().equals(key)) {
						value = lst[i].getValue();
						break;
					}
				}
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return value;
	}
	
	 
	


	public static void SetCookieValue(HttpServletResponse response, String key,
			String value) {
		try {
			Cookie ck = new Cookie(key, value);
			response.addCookie(ck);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	 
	public static void ClearCookie(HttpServletRequest request,
			HttpServletResponse response, String key) {
		try {
			Cookie[] lst = request.getCookies();
			for (int i = 0; i < lst.length; i++) {
				if (lst[i].getName().equals(key)) {
					Cookie cookie = new Cookie(lst[i].getName(), null);
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 查询一个字符是否在一个数组中
	 * 
	 * 
	 * @param myStrings 需要查询的字符串数组
	 * @param key 需要检查的字符
	 * @return 存在返回true否则返回false;
	 */
	public static boolean inArray(String[] myStrings, String key) {

		for (int i = 0; i < myStrings.length; i++) {
			if (myStrings[i].equals(key)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 字符串截取
	 * 
	 * @param fieldValue
	 *            被截取字符串
	 * @param fix
	 *            要查询的字符串
	 * @param isleft
	 *            向那个方向截取
	 * @return 如果 “要查询的字符串”没有找到并且是，放回原来字符串
	 */
	public static String leftAndRight(String fieldValue, String fix,
			Boolean isleft) {
				int istart = fieldValue.indexOf(fix);

		if (isleft == true) {
			if (istart > 0) {
				return fieldValue.substring(0, istart);
			} else {
				return fieldValue;
			}
		} else {
			if (istart > 0) {
				return fieldValue.substring(istart + 1, fieldValue.length());
			} else {
				return "";
			}
		}
	}
	
	/**
	 * 读取文件并以字节数组的形式返回
	 * @param file 文件句柄
	 * @return 包含文件完整内容的字节数组
	 * @throws IOException
	 */
	public static byte[] GetBytesFromFile(File file) throws IOException {
		byte[] bytes = new byte[0];
		InputStream is = null;
		try {
			if (file.exists()) {
				is = new FileInputStream(file);
				long length = file.length();

				bytes = new byte[(int) length];

				int offset = 0;

				int numRead = 0;

				while ((offset < bytes.length)
						&& ((numRead = is.read(bytes, offset, bytes.length
								- offset)) >= 0)) {
					offset += numRead;
				}

			}
		} catch (Exception ex) {
			if (is != null) {
				is.close();
			}

		}
			return bytes;
	}
	
	/**
	 * 读取文件并以字节数组的形式返回
	 * @param fileName 文件的路径（目录+完整文件名）
	 * @return  包含文件完整内容的字节数组
	 * @throws IOException
	 */
	public static byte[] GetBytesFromFile(String fileName) throws IOException {
			return GetBytesFromFile (new File(fileName));
	}

	
	public static void Write2File(String fileName, String content) {
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	

}
